package com.qianfeng.yime.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.qianfeng.yime.R;
import com.qianfeng.yime.model.City;

import java.util.List;

/**
 * Created by IDEA
 * User : SL
 * on  2015/3/11.
 * 17:31
 */
public class CityLocationListAdapter extends BaseAdapter {

    private LayoutInflater inflater;
    private List<City> cities;

    public CityLocationListAdapter(Context context, List<City> cities) {
        if (context != null) {
            inflater = LayoutInflater.from(context);
        }else {
            throw new IllegalArgumentException("context must not null");
        }
        this.cities = cities;
    }

    @Override
    public int getCount() {
        int ret = 0;
        if (cities != null) {
            ret = cities.size();
        }
        System.out.println("ret = " + ret);
        return ret;
    }

    @Override
    public Object getItem(int position) {
        Object ret = null;
        if (cities != null) {
            ret = cities.get(position);
        }
        return ret;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View ret = null;

        City city = cities.get(position);
        String letter = city.getLetter();
        String name = city.getName();

        if (convertView != null) {
            ret = convertView;
        }else {
            ret = inflater.inflate(R.layout.item_city_name, parent, false);
        }

        ViewHolder holder = (ViewHolder) ret.getTag();

        if (holder == null) {
            holder = new ViewHolder();

            holder.letterHolder = (TextView) ret.findViewById(R.id.text_item_city_letter);
            holder.nameHolder = (TextView) ret.findViewById(R.id.text_item_city_name);

            ret.setTag(holder);
        }

        if (position == 0){
            holder.letterHolder.setVisibility(View.VISIBLE);
            holder.letterHolder.setText(letter);
            holder.nameHolder.setText(name);
        }else if (!cities.get(position - 1).getLetter().equals(letter)){
            holder.letterHolder.setVisibility(View.VISIBLE);
            holder.letterHolder.setText(letter);
            holder.nameHolder.setText(name);
        }else {
            holder.letterHolder.setVisibility(View.GONE);
            holder.letterHolder.setText(letter);
            holder.nameHolder.setText(name);
        }

        return ret;
    }

    private class ViewHolder{
        private TextView letterHolder;
        private TextView nameHolder;
    }
}
